<template>
  <jke-modal
    :visible.sync="jkeForm.visible"
    :width="1200"
    :title="jkeForm.title"
    :fullscreen.sync="jkeForm.fullscreen"
    :switchFullscreen="jkeForm.switchFullscreen"
  >
    <!--  -->
    <crumbs @goBack="goBack" :superiorMenu="['技术管理', '工艺路线']" :currentMenu="jkeForm.title"></crumbs>
    <div class="form-body" :style="{ height: jkeForm.fullscreen ? 'calc(100vh - 110px)' : 'auto' }">
      <a-card title="基础信息" :bordered="false" style="margin-top: 12px">
        <a-form :form="form" @submit="handleSubmit" layout="vertical">
          <a-form-item label="工艺编号">
            <a-input
              v-decorator="[
                'processRouteCode',
                {
                  rules: [
                    {
                      required: false,
                      message: '请输入工艺编号或自动生成',
                    },
                    {
                      message: '该值不可用，系统中已存在！',
                    },
                  ],
                },
              ]"
              :maxLength="21"
              placeholder="不输入则自动生成"
            />
            <!-- validator: (rule, value, callback) => validateDuplicateValue('mess_product_craft', 'craft_code', value,
            queryId, callback), -->
            <!--            <span class="btn-text code-btn" @click="genEntityCode" v-if="!isEdit">自动生成</span>-->
          </a-form-item>
          <!-- </a-form> -->
          <!-- <a-form :form="form" @submit="handleSubmit" layout="vertical"> -->
          <a-form-item label="工艺名称">
            <a-input
              v-decorator="['processRouteName', { rules: [{ required: true, message: '请输入工艺名称' }] }]"
              placeholder="请输入工艺名称"
              :maxLength="50"
            />
          </a-form-item>
          <a-form-item></a-form-item>
        </a-form>
      </a-card>
      <a-card title="工序列表" style="margin-top: 12px; margin-bottom: 12px; flex: 1" :bordered="false">
        <a-col :span="24" style="margin-bottom: 38px">
          <j-editable-table
            :ref="refKeys[0]"
            :loading="processTable.loading"
            :rowNumber="true"
            rowNumberText="序号"
            :columns="processTable.columns"
            :allColumns="processTable.allColumns"
            :dataSource="processTable.dataSource"
            :maxHeight="3000000"
            :disabled="formDisabled"
            :actionButton="true"
            @valueChange="valueChange"
            :dragSort="true"
            :rowSelection="true"
            :showSetBar="true"
            :EntityName="'PROCESSESROUTEMANAGE'"
            :addActionButton="false"
          >
            <span slot="options">
              <a-button @click="openItProcess('all')" type="primary" icon="plus" style="margin-right: 20px">添加</a-button>
              <!-- <a-button @click="openItCircuit">选择生产流程</a-button> -->
            </span>
            <template v-slot:processCodeName="props">
              <a-input
                @click="openItProcess(props)"
                :value="props.value"
                placeholder="请选择"
                :read-only="true"
                :class="props.value ? 'has-value' : ''"
              >
                <a-icon slot="suffix" type="down" style="color: #cdcdcd; font-size: 12px" class="down-icon" />
                <a-icon
                  slot="suffix"
                  type="close-circle"
                  theme="filled"
                  class="close-icon"
                  @click="getSelectValueProcess(false, '', [], props.rowId)"
                />
              </a-input>
            </template>
            <template v-slot:processWorkRate="props">
              <a-input
                :value="props.value"
                placeholder="请输入"
                @input="(e) => inputNums(props, e, 'processWorkRate', 'processTable')"
              />
            </template>
            <template v-slot:excessWorkRate="props">
              <a-input
                :value="props.value"
                placeholder="请输入"
                @input="(e) => inputNums(props, e, 'excessWorkRate', 'processTable')"
              />
            </template>
            <template v-slot:processRequire="props">
              <a-input
                :value="props.value"
                placeholder="请输入"
                :maxLength="500"
                @input="(e) => inputRequire(props, e, 'processRequire', 'processTable')"
              />
            </template>
            <template v-slot:action="props">
              <a-popconfirm
                title="是否删除?"
                ok-text="是"
                cancel-text="否"
                @confirm="handleDelete(props)"
                @cancel="cancel"
              >
                <a style="padding-left: 3px; color: #f25643">删除</a>
              </a-popconfirm>
            </template>
          </j-editable-table>
        </a-col>
      </a-card>
    </div>

    <div class="footer-submit" :class="jkeForm.fullscreen ? 'form-footer' : ''">
      <a-button @click="goBack" class="submitBtn" style="margin-right: 10px"> 取消</a-button>
      <a-button type="primary" :loading="loadingSubmit" class="submitBtn" @click="saveForm"> 提交</a-button>
    </div>
    <goodsTableSelect ref="tableSelect" @getSelectValue="getSelectValue" :key="indexGoods"></goodsTableSelect>
    <tableSelect
      ref="tableSelectProcess"
      @getSelectValue="getSelectValueProcess"
      :key="indexProcess"
      @cancel="searchResetProcess"
    >
    </tableSelect>
    <tableSelect ref="tableSelectCircuit" @getSelectValue="getSelectValueCircuit" :key="indexCircuit">
      <div slot="head">
        <div class="uni-card" style="background: #fff">
          <a-form-model ref="ruleForm" layout="inline" :model="filterFormCircuit">
            <a-form-model-item label="流程编号">
              <a-input v-model="filterFormCircuit.flowCode" placeholder="请输入" />
            </a-form-model-item>
            <a-form-model-item label="流程名称">
              <a-input v-model="filterFormCircuit.flowName" placeholder="请输入" />
            </a-form-model-item>
            <a-form-model-item>
              <a-button @click="searchCircuit()" type="primary"> 搜索</a-button>
              <a-button style="margin-left: 10px" @click="searchResetCircuit">重置</a-button>
            </a-form-model-item>
          </a-form-model>
        </div>
      </div>
    </tableSelect>
  </jke-modal>
</template>
<script>
import { FormTypes } from '@/utils/JEditableTableUtil'
import tableSelect from '@/components/tableSelect'
import goodsTableSelect from '@/components/goodsTableSelect'
import crumbs from '@/components/crumbs.vue'
import {
  basicProcessRouteInfoAdd,
  basicProcessRouteInfoEdit,
  basicProcessRouteInfoQueryById,
  queryFlowProcessListByFlowId,
  getDictModel,
  productGetDictPageList,
  checkByGoodsIdt,
} from '@/api/goodsManagement'
import FileUpload from '@/components/fileActions/FileUpload.vue'
import { API } from '@/api/requestFzs'
import { validateDuplicateValue } from '@/utils/util'
import { fourFloatNum, clearNoNum } from '@/utils/util'
import { getAction } from '@/api/manage'
import { detailTableForm } from '@api/productOrder'
import moment from 'moment/moment'
import { APILX } from '@api/requestLx'

export default {
  data() {
    return {
      jkeForm: {
        title: '新建工艺',
        visible: false,
        fullscreen: true,
        switchFullscreen: true,
      },
      //下拉改弹窗
      indexGoods: 0.1,
      columns: [
        {
          title: '物品编号',
          width: 180,
          ellipsis: true,
          dataIndex: 'goodsCode',
          searchKey: 'goodsCode',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'goodsCode',
          },
        },
        {
          title: '物品名称',
          width: 180,
          ellipsis: true,
          dataIndex: 'goodsName',
          searchKey: 'goodsName',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'goodsName',
          },
        },
        {
          title: '规格',
          width: 100,
          ellipsis: true,
          dataIndex: 'spec',
          searchKey: 'spec',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'spec',
          },
        },
        {
          title: '物品类型',
          width: 100,
          ellipsis: true,
          dataIndex: 'typeText',
          searchKey: 'type',
          type: 'select',
          scopedSlots: {
            filterDropdown: 'selectDropdown',
            filterIcon: 'selectIcon',
            customRender: 'typeText',
          },
        },
        {
          title: '物品分类',
          width: 100,
          ellipsis: true,
          dataIndex: 'categoryText',
          searchKey: 'category',
          type: 'tree',
          scopedSlots: {
            filterDropdown: 'selectDropdown',
            filterIcon: 'selectIcon',
            customRender: 'categoryText',
          },
        },
      ],
      goodsValue: '',
      goodsText: '',
      filterForm: {
        goodsCode: '', //物品编号
        goodsName: '', //物品名称
      },
      //下拉改弹窗结束
      //下拉改弹窗
      indexProcess: 0.2,
      processRowId: '',
      columnsProcess: [
        {
          title: '工序编号',
          dataIndex: 'processesCode',
          ellipsis: true,
          // fixed: 'left',
          width: 200,
          searchIndex: 'processesCode',
          scopedSlots: {
            filterDropdown: 'searchDropdown',
            filterIcon: 'searchIcon',
            customRender: 'processesCode',
          },
        },
        {
          title: '工序名称',
          dataIndex: 'processesName',
          ellipsis: true,
          // fixed: 'left',
          width: 180,
          searchIndex: 'processesName',
          options: [],
          scopedSlots: {
            filterDropdown: 'searchDropdown',
            filterIcon: 'searchIcon',
            customRender: 'processesName',
          },
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          ellipsis: true,
          width: 180,
          searchIndex: 'createTime',
          sorter: true,
          scopedSlots: {},
        },
        {
          title: '更新时间',
          dataIndex: 'updateTime',
          ellipsis: true,
          width: 180,
          searchIndex: 'updateTime',
          sorter: true,
          scopedSlots: {},
        },
        {
          title: '创建人',
          dataIndex: 'createBy',
          ellipsis: true,
          width: 180,
          searchIndex: 'createBy',
          options: [],
          scopedSlots: {
            filterDropdown: 'selectPeople1',
            filterIcon: 'dateIcon',
          },
        },
        {
          title: '更新人',
          dataIndex: 'updateBy',
          ellipsis: true,
          width: 180,
          searchIndex: 'updateBy',
          options: [],
          scopedSlots: {
            filterDropdown: 'selectPeople2',
            filterIcon: 'dateIcon',
          },
        },
      ],
      processValue: '',
      processText: '',
      filterFormProcess: {
        processCode: '', //工序编号
        processName: '', //工序名称
      },
      //下拉改弹窗结束
      // -----流程弹窗配置-begin-----
      indexCircuit: 0.3,
      columnsCircuit: [
        {
          title: '流程编号',
          dataIndex: 'flowCode',
          key: 'flowCode',
          width: 180,
          ellipsis: true,
        },
        {
          title: '流程名称',
          dataIndex: 'flowName',
          key: 'flowName',
          width: 180,
          ellipsis: true,
        },
        {
          title: '组成工序',
          dataIndex: 'process',
          width: 180,
          key: 'process',
          ellipsis: true,
        },
      ],
      circuitValue: '',
      circuitText: '',
      filterFormCircuit: {
        flowCode: '',
        flowName: '',
      },
      // -----流程弹窗配置-end-----
      typeList: [], //类型字典
      processParam: {
        pageNo: 1,
        pageSize: 999,
      },
      validateDuplicateValue, //自动生成编码
      queryId: '',
      loadingSubmit: false, //防止多次提交
      submitApi: basicProcessRouteInfoAdd,

      isEdit: false,
      dictOptionsGoodsUnit: '', //基本单位 字典
      attachment: '', //附件
      // 辅助单位
      refKeys: ['processTable'],
      tableKeys: ['processTable'],
      processList: [], //表格-工序 数据
      processTable: {
        loading: false,
        dataSource: [],
        allColumns: [
          {
            title: '工序id',
            key: 'processId',
            dataIndex: 'processId',
            type: FormTypes.hidden,
          },
          {
            title: '工序',
            dataIndex: 'processesName',
            key: 'processesName',
            width: '20%',
          },
        ],
        columns: [
          {
            title: '工序id',
            key: 'processId',
            dataIndex: 'processId',
            type: FormTypes.hidden,
          },
          {
            title: '工序',
            dataIndex: 'processesName',
            key: 'processesName',
            width: '20%',
          },
        ],
      },
      formTypeExtendedFields: [],
      formLayout: 'horizontal',
      form: this.$form.createForm(this, { name: 'coordinated' }),
      goodsId: '',
    }
  },
  components: {
    FileUpload,
    crumbs,
    tableSelect,
    goodsTableSelect,
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
  },
  methods: {
    // edittable输入数字格式化
    inputNums(props, e, key, ref) {
      this.$refs[ref].setValues([
        {
          rowKey: props.rowId, // 行的id
          values: {
            // 在这里 values 中的 specifications 是你 columns 中配置的 key
            [key]: clearNoNum(e.target.value),
          },
        },
      ])
    },
    inputRequire(props, e, key, ref) {
      this.$refs[ref].setValues([
        {
          rowKey: props.rowId, // 行的id
          values: {
            // 在这里 values 中的 specifications 是你 columns 中配置的 key
            [key]: e.target.value,
          },
        },
      ])
    },
    // -----选择流程事件-begin-----
    openItCircuit() {
      let goods = this.form.getFieldValue('goodsName')
      if (!goods) {
        this.form.validateFields(['goodsName'])
        this.$antdMessage.info('请先选择物料')
        return
      }
      let par = {
        list: `/prodset/messProductFlow/queryFlowListByGoodsId?goodsId=${this.goodsValue}`,
        visible: true, //弹窗开启
        title: '工序', //标题名称
        multi: false, //是否多选
        columns: this.columnsCircuit, //表格配置
        value: this.circuitValue, //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'id', //需要拿到数据的key，如：id，userId等
        text: this.circuitText, //回显的中文，如：'张三'
        textKey: 'processName', //回显的中文key
      }
      this.$refs.tableSelectCircuit.getInit(par)
    },
    getSelectValueCircuit(id, text, item) {
      console.log(id, text, item)
      if (!id) {
        return
      }
      this.indexCircuit += 1 //重置组件去除表格默认勾选数据，让自己赋值的数据回显（重要！！！）
      this.circuitValue = id
      this.circuitText = text
      console.log(id, text, item, '列表选择的数据')
      queryFlowProcessListByFlowId({ flowId: id }).then((res) => {
        if (res.result) {
          let newData = res.result.records || []
          this.$refs.processTable.initialize()
          newData = newData.map((obj) => {
            obj = {
              processId: obj.processId,
              processCodeName: `${obj.processCode}-${obj.processName} `,
              processWorkUnit: obj.processWorkUnit || '',
              processRequire: obj.processRequire || '',
              excessWorkRate: obj.excessWorkRate,
              processName: obj.processName,
              processWorkRate: '1',
            }
            return obj
          })
          this.processTable.dataSource = newData
        }
      })
    },
    searchResetCircuit() {
      this.filterFormCircuit.flowCode = ''
      this.filterFormCircuit.flowName = ''
      this.$refs.tableSelectCircuit.searchReset()
    },
    searchCircuit() {
      this.$refs.tableSelectCircuit.searchQuery(this.filterFormCircuit)
    },
    // -----选择流程事件-end-----
    searchResetProcess() {
      this.filterFormProcess.processCode = ''
      this.filterFormProcess.processName = ''
      this.$refs.tableSelectProcess.searchReset()
    },
    searchProcess() {
      this.$refs.tableSelectProcess.searchQuery(this.filterFormProcess)
    },
    searchResetGoods() {
      this.filterForm.goodsCode = ''
      this.filterForm.goodsName = ''
      this.$refs.tableSelect.searchReset()
    },
    searchGoods() {
      this.$refs.tableSelect.searchQuery(this.filterForm)
    },
    // 物料下拉改弹窗
    openIt() {
      let goodsUrl = ''
      if (this.isEdit) {
        goodsUrl = `/mess/messProductCraft/goods/list?id=${this.goodsId}`
      } else {
        goodsUrl = '/mess/messProductCraft/goods/list'
      }
      let par = {
        list: goodsUrl,
        visible: true, //弹窗开启
        title: '物料', //标题名称
        multi: false, //是否多选
        columns: this.columns, //表格配置
        value: this.goodsValue, //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'id', //需要拿到数据的key，如：id，userId等
        text: this.goodsText, //回显的中文，如：'张三'
        textKey: 'goodsName', //回显的中文key
      }
      this.$refs.tableSelect.getInit(par)
    },
    getSelectValue(id, text, item) {
      console.log(537, id, text, item)
      if (!id) {
        this.form.setFieldsValue({
          goodsName: '',
          spec: undefined,
          basicUnit: undefined,
          type: undefined,
        })
        this.goodsText = ''
        this.goodsValue = ''
        return
      }
      this.indexGoods += 1 //重置组件去除表格默认勾选数据，让自己赋值的数据回显（重要！！！）
      this.goodsValue = id
      this.goodsText = text
      console.log(id, text, item, '列表选择的数据')
      this.goodsBaseInfoChange(id, item[0])
    },
    // 工序下拉改弹窗
    async openItProcess(props) {
      let res = await APILX.formTypeExtendedFieldList({ formType: 7 })
      if (res.code == 200 && res.result) {
        let formTypeExtendedFields = res.result
        let columnsa = []
        formTypeExtendedFields.forEach((fields) => {
          let tableHead = {
            title: fields.fieldName,
            dataIndex: 'extDataJson.' + fields.fieldKey,
            ellipsis: true,
            width: 150,
            searchIndex: 'extDataJson.' + fields.fieldKey,
            scopedSlots: {
              filterDropdown: 'searchDropdown',
              filterIcon: 'searchIcon',
            },
          }
          columnsa.push(tableHead)
        })
        this.columnsProcess = [...this.columnsProcess, ...columnsa]
      }
      let values = ''
      if(props=='all'){
        values = this.processTable.dataSource.map(item=>item.id).join()
      }else{
        values = this.processValue
      }

      let par = {
        list: '/basic/basicProductionProcesses/list',
        visible: true, //弹窗开启
        title: '工序', //标题名称
        multi: true, //是否多选
        columns: this.columnsProcess, //表格配置
        value: values, //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'id', //需要拿到数据的key，如：id，userId等
        text: this.processText, //回显的中文，如：'张三'
        textKey: 'processName', //回显的中文key
        action: 'post',
      }
      this.$refs.tableSelectProcess.getInit(par)
    },
    getSelectValueProcess(id, text, item, rowId) {
      console.log(571, id, text, item, rowId)
      item.forEach((e) => {
        // this.$refs.processTable.push({
        //   processesName: e.processesName,
        //   id: e.id,
        // })
        this.processTable.dataSource.push({
          ...e,
        })
      })

      this.processTable.columns.forEach((item) => {
        this.processTable.dataSource.forEach((el, index) => {
          console.log('formTypeExtendedFields', item, el.extDataJson)
          for (let key in el.extDataJson) {
            if (item.key === key) {
              console.log(item)
              this.$set(this.processTable.dataSource[index], item.key, el.extDataJson[key])
            }
          }
        })
      })
    },
    // 工序 change
    onChangeSelect(obj) {
      console.log(this.processRowId, 'this.processRowId')
      let tableValue = this.$refs.processTable.getValuesSync({ validate: false }).values
      for (let i = 0; i < tableValue.length; i++) {
        const v = tableValue[i]
        if (v.processId == this.processValue) {
          if (v.id == this.processRowId) {
            return
          }
          this.$refs.processTable.removeRows(this.processRowId)
          this.$antdMessage.warning('该工序已存在，请直接修改数据')
          return
        }
      }
      this.$refs.processTable.setValues([
        {
          rowKey: this.processRowId, // 行的id
          values: {
            // 在这里 values 中的 specifications 是你 columns 中配置的 key
            processId: this.processValue,
            processCodeName: `${obj.processCode}-${obj.processName} `,
            processWorkUnit: obj.processWorkUnit || '',
            processRequire: obj.processRequire || '',
            excessWorkRate: obj.excessWorkRate,
            processName: obj.processName,
            processWorkRate: '1',
          },
        },
      ])
      const { error, values } = this.$refs.processTable.getValuesSync({ validate: true })
      console.log(values, 'valuesvaluesvalues')
    },
    // 下拉搜索
    filterOption(input, option) {
      console.log('inputoption', input, option)
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    /* 匹配正数,小数点后2位 */
    fourFloatNum(value) {
      //先把非数字的都替换掉，除了数字和.,
      // if (value.charAt(0) == 0 || value.charAt(0) == '.') {
      //   value = ''
      // }
      if (value.charAt(0) == '.') {
        value = ''
      }
      value = value.replace(/[^\d.]/g, '')
      value = value.replace(/^(\-)*(\d+)\.(\d{4}).*$/, '$1$2.$3')
      return value
    },

    getProcess() {
      productGetDictPageList(this.processParam).then((res) => {
        res.result.records.forEach((item) => {
          this.processList.push(item)
        })
      })
    },
    popupScroll(e) {
      const { scrollHeight, scrollTop, clientHeight } = e.target
      if (scrollHeight - scrollTop - clientHeight < 1) {
        this.processParam.pageNo++
        this.getProcess()
      }
    },
    /* 自动生成 */
    genEntityCode() {
      API.genEntityCode({ entityCode: 'MESS_PRODUCT_CRAFT' }).then((res) => {
        if (res.code == 200) {
          this.form.setFieldsValue({
            craftCode: res.result,
          })
        } else {
          this.$antdMessage.error(res.message)
        }
      })
    },
    valueChange(type, row, column, value) {
      console.log(type, row, column, value, 'value change type')
      // debugger
      if (type.column.key == 'processWorkRate') {
        if (type.value) {
          this.$refs.processTable.setValues([
            {
              rowKey: type.row.id, // 行的id
              values: {
                // 在这里 values 中的 specifications 是你 columns 中配置的 key
                processWorkRate: fourFloatNum(type.value),
              },
            },
          ])
        }
      }
      if (type.column.key == 'excessWorkRate') {
        if (type.value) {
          this.$refs.processTable.setValues([
            {
              rowKey: type.row.id, // 行的id
              values: {
                // 在这里 values 中的 specifications 是你 columns 中配置的 key
                excessWorkRate: fourFloatNum(type.value),
              },
            },
          ])
        }
      }
    },
    // 物料下拉选择
    goodsBaseInfoChange(value, item) {
      this.form.setFieldsValue({
        goodsName: this.goodsText || '',
        spec: item.spec || '',
        basicUnit: item.basicUnitText || '',
        type: item.type || '',
      })
      this.getGoodsFlow(value)
    },
    getGoodsFlow(value) {
      getAction(`/prodset/messProductFlow/queryFlowListByGoodsId?goodsId=${value}`).then((res) => {
        if (res.result.total && res.result.total === 1) {
          let flowInfo = res.result.records[0]
          this.circuitValue = flowInfo.id
          this.circuitText = flowInfo.flowName
          queryFlowProcessListByFlowId({ flowId: flowInfo.id }).then((item) => {
            if (item.result) {
              let newData = item.result.records || []
              this.$refs.processTable.initialize()
              newData = newData.map((obj) => {
                obj = {
                  processId: obj.processId,
                  processCodeName: `${obj.processCode}-${obj.processName} `,
                  processWorkUnit: obj.processWorkUnit || '',
                  processRequire: obj.processRequire || '',
                  excessWorkRate: obj.excessWorkRate,
                  processName: obj.processName,
                  processWorkRate: '1',
                }
                return obj
              })
              this.processTable.dataSource = newData
            }
          })
        }
      })
    },
    /* 获取编辑详情 */
    initForm(id, copy = false) {
      Object.assign(this.$data, this.$options.data.call(this))
      this.jkeForm.visible = true
      this.queryId = id

      let column = []
      let formTypeExtendedFields = []
      // 获取工序自定义表单字段;
      // 获取工序自定义表单字段;
      APILX.formTypeExtendedFieldList({ formType: 7 }).then((res) => {
        if (res.code == 200 && res.result) {
          this.formTypeExtendedFields = res.result
          formTypeExtendedFields = res.result || []
          formTypeExtendedFields.forEach((field) => {
            let col = {
              title: field.fieldName,
              key: field.fieldKey,
              type: FormTypes.input,
              toolTip: field.explanationPrompt, // 表头的提示文字描述
              placeholder: field.placeholder,
              width: '15%',
            }
            if (field.fieldMust == 2) {
              col.isrequired = true
              col.validateRules = [
                {
                  required: true, // 必填
                  message: `${field.fieldName}不能为空`, // 提示的文本
                },
              ]
            } else if (field.fieldMust == 1) {
              col.disabled = true
            } else {
              col.disabled = false
            }
            // 这里根据自定义字段的类型，设置为普通文本输入还是数字输入
            if (field.fieldType == 1) {
              col.type = FormTypes.input
            } else if (field.fieldType == 2) {
              col.type = FormTypes.input
            } else if (field.fieldType == 3) {
              col.type = FormTypes.inputNumber
              const maxLength = field.fieldLength // 获取最大长度变量的值
              const pattern = new RegExp(`^\\d{1,${maxLength}}$`)
              if (!(col.validateRules && col.validateRules.length)) {
                col.validateRules = []
              }
              col.validateRules.push({
                pattern: pattern,
                message: `只能输入最大长度为${maxLength}的整数`,
              })
            }

            column.push(col)
          })

          this.processTable.columns = this.processTable.columns.concat(column)
          this.processTable.columns = this.processTable.columns.filter((item) => item.type !== 'hidden')
          this.processTable.allColumns = this.processTable.columns.filter((item) => item.type !== 'hidden')
        }
      })

      if (id) {
        if (copy) {
          this.jkeForm.title = '新建工艺'
          this.queryId = null
          this.submitApi = basicProcessRouteInfoAdd
        } else {
          this.jkeForm.title = '编辑工艺'
          this.submitApi = basicProcessRouteInfoEdit
          this.isEdit = true
        }

        basicProcessRouteInfoQueryById({ id: id })
          .then((res) => {
            if (res.code == 200) {
              res.result.basicProcessRouteDetailDtooList.forEach((item) => {
                item.processCodeName = `${item.processCode}-${item.processName} `
              })
              if (copy) {
                res.result.processRouteCode = ''
              }
              this.form.setFieldsValue(res.result)
              this.attachment = res.result.attachment
              this.processTable.dataSource = res.result.basicProcessRouteDetailDtooList
              this.processTable.dataSource.forEach((item) => {
                item.id = item.processesId
              })
              this.goodsValue = res.result.goodsId
              this.goodsText = res.result.goodsName
              this.goodsId = res.result.goodsId
            }
          })
          .finally(() => {
            formTypeExtendedFields.forEach((item) => {
              // console.log('formTypeExtendedFields', formTypeExtendedFields, this.processTable.dataSource)
              this.processTable.dataSource.forEach((el, index) => {
                for (let key in el.extDataJson) {
                  if (item.fieldKey === key) {
                    console.log(item, 'item')
                    this.$set(this.processTable.dataSource[index], item.fieldKey, el.extDataJson[key])
                  }
                }
              })
            })
          })
      } else {
        this.jkeForm.title = '新建工艺'
        this.submitApi = basicProcessRouteInfoAdd
      }
    },
    //表格 工序 下拉选择数据接口
    // getdata() {
    //   // 字典接口
    //   getDictModel({ dictCode: 'wms_goods_unit' }).then((res) => {
    //     this.dictOptionsGoodsUnit = res.result
    //     this.processTable.columns[2].options = res.result
    //   })
    // },
    // 分类下拉选择
    handleSelectClassify(value) {
      console.log(value)
      this.form.setFieldsValue({
        note: `Hi, ${value === 'male' ? 'man' : 'lady'}!`,
      })
    },
    /* 面包屑返回 */
    goBack() {
      this.jkeForm.visible = false
    },
    /* 获取附件 */
    getFileList(v) {
      this.attachment = v
      console.log('上传的附件id：', v)
    },
    // 提交
    saveForm() {
      const { error, values } = this.$refs.processTable.getValuesSync({ validate: true })
      if (!error) {
        let noZero = true
        values.forEach((item, index) => {
          // if (item.processWorkRate == '0' || item.processWorkRate == '0.') {
          //   this.$antdMessage.error('报工配比不能为0')
          //   noZero = false
          // }
          // if (item.processWorkRate.charAt(0) == '0') {
          //   if (item.processWorkRate.length > 1 && item.processWorkRate.charAt(1) !== '.') {
          //     this.$antdMessage.error('报工配比输入格式有误')
          //     noZero = false
          //   }
          // }
        })
        if (noZero) {
          let subValues = values.map((item, index) => {
            let obj = {
              sort: index + 1,
              productionProcessesId: item.id,
              extDataJson: {},
            }

            if (this.formTypeExtendedFields.length != 0) {
              this.formTypeExtendedFields.forEach((ele) => {
                ;[(obj.extDataJson[ele.fieldKey] = item[ele.fieldKey])]
              })
            }
            return obj
          })
          this.handleSubmit(subValues)
        }
      }
    },
    handleSubmit(tableValue) {
      this.form.validateFields((err, values) => {
        if (!err) {
          // if (values.purchaseDate) {
          //   values.purchaseDate = moment(values.purchaseDate).format('YYYY-MM-DD HH:mm:ss')
          // }
          let parameters = {
            ...values,
            attachment: this.attachment,
            basicProcessRouteDetailDtooList: tableValue,
            goodsId: this.goodsValue,
          }
          if (this.isEdit) {
            parameters.id = this.queryId
          }
          this.loadingSubmit = true
          this.submitApi(parameters).then((res) => {
            if (res.code == 200) {
              this.loadingSubmit = false
              let subMsg = this.isEdit ? '工艺编辑成功！' : '工艺创建成功！'
              this.$antdMessage.success(subMsg)
              this.$emit('refresh')
              this.goBack()
            } else {
              this.loadingSubmit = false
              this.$antdMessage.error(res.message)
            }
          })
        }
      })
    },
    // 辅助单位-删除
    handleDelete(props) {
      let { rowId, target } = props
      target.removeRows(rowId)
    },
    cancel() {},
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';

.flex(@jc,@ai,@fd:row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}

/deep/ .ant-form-vertical {
  display: flex;
  justify-content: space-between;

  .ant-form-item {
    width: 30%;
  }
}

.form-body {
  // height: calc(100vh - 110px);
  // overflow-y: scroll;
  display: flex;
  flex-direction: column;
}

.submitBtn {
  .flex(flex-end, center);
  padding: 8px;
  justify-content: center;
}

.code-btn {
  position: absolute;
  right: 0;
  top: -34.5px;
}
/deep/ .ant-modal-body {
  background-color: #eee !important;
  overflow: hidden;
}
.form-body {
  height: calc(100vh - 110px);
  display: flex;
  flex-direction: column;
  overflow: auto;
}
</style>
